package com.koron.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.koron.auth.aop.LoginLog;
import com.koron.auth.service.StaffService;
import com.koron.bean.app.AppSimpleBean;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgVo;
import com.koron.bean.system.staff.Constant;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.system.SystemCacheUtil;
import com.koron.common.core.business.workflow.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author jzp
 * @since 2023/6/29
 */
@Service("iamAuthService")
@Slf4j
@RefreshScope
public class IamAuthServiceImpl {

    @Autowired
    StaffService staffService;

    @Value("${sso.redirectPage}")
    private String redirectPage;

    @Value("${sso.redirectWorkStationPage}")
    private String workStationPage;

    /*
    https://认证接口地址/idp/oauth2/authorize?redirect_uri=https://www.baidu.com&state=xxxx&client_id=xxxxx&response_type=code
    https://iam-swdev.gdhwater.com:6443/idp/oauth2/authorize?redirect_uri=http://10.11.228.110:30001/eam-service-auth/auth/iamSsoLoginRedirect.htm&state=iam&client_id=EAM2&response_type=code
     */
    @Value("${sso.iamAuthorizeUrl:null}")
    private String authorizeUrl;

    /*
    https://认证接口地址/idp/oauth2/getToken
    https://iam-swdev.gdhwater.com:6443/idp/oauth2/getToken
     */
    @Value("${sso.iamGetTokenUrl:null}")
    private String getTokenUrl;

    /*
    https://认证接口地址/idp/oauth2/getUserInfo
    https://iam-swdev.gdhwater.com:6443/idp/oauth2/getUserInfo
     */
    @Value("${sso.iamGetUserInfoUrl:null}")
    private String getUserInfoUrl;

    @Value("${sso.clientId:null}")
    private String clientId;

    @Value("${sso.clientSecret:null}")
    private String clientSecret;


    /**
     * 获取授权Token接口
     */
    private JSONObject getAccountByCode(String code) {
        // https://认证接口地址/idp/oauth2/getToken?client_id=xxxxxx&grant_type=authorization_code&code=xxxxxx&client_secret=xxxxxx

        String path = getTokenUrl + "?client_id=" + clientId + "&grant_type=authorization_code&code=" + code + "&client_secret=" + clientSecret;
        log.info("获取用户信息：{}", path);
        //ticket回调获取登录有效用户账户信息
        String jsonStr = HttpUtil.sendPost(path);
        log.info("ticket验证返回数据:{}", jsonStr);

        return JSONObject.parseObject(jsonStr);
    }

    /**
     * 获取授权Token接口
     */
    private JSONObject getUserInfoByToken(String accessToken) {
        // https://认证接口地址/idp/oauth2/getUserInfo?access_token=skiew234i3i4o6uy77b4k3b3v2j1vv53j&client_id=xxxxxx
        // https://iam-swdev.gdhwater.com:6443/idp/oauth2/getUserInfo?access_token=df1ca6dd430b3c7304ffbb4accaaaff0&client_id=EAM2

        String path = getUserInfoUrl + "?access_token=" + accessToken + "&client_id=" + clientId;
        log.info("获取用户信息：{}", path);
        //ticket回调获取登录有效用户账户信息
        String jsonStr = cn.hutool.http.HttpUtil.get(path);
        log.info("ticket验证返回数据:{}", jsonStr);

        return JSONObject.parseObject(jsonStr);
    }


    //直接重定向到前台
    public void ssoLoginRedirect(String code, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //String str = "http://10.11.228.43:8080/#/appChange?ticket=";

        String accessToken = null;
        //在此判断如果用户只有一个租户、一个组织、一个身份，登录之后直接跳转到首页
        if (!StringUtils.isEmpty(code)) {

            JSONObject msg = getAccountByCode(code);

            // 查询条件字符串转对象，查询数据结果
            // ticket有错，可返回异常信息，前端可重定向到系统登录界面，也可在此用response.sendRedirect直接重定向到登录界面
            accessToken = msg.getString("access_token");
        }

        log.info("auth 重定向前台页面:{}", redirectPage);
        response.sendRedirect(redirectPage + accessToken);
    }


    /*
     * 功能描述
     * @author zhouj
     * @date 2021/11/12 10:47
     * @param [ticket, account, request, response]
     * @return com.koron.bean.base.Response
     * desc ticket:集团单点登录使用
     */
    @LoginLog
    public Response getSsoLoginUserInfo(String accessToken, String account, HttpServletRequest request, HttpServletResponse response) throws IOException {

        EamUser eamUser;

        String token = null;

        if (StringUtils.isEmpty(account)) {
            //获取请求里面  原有的token信息. 若原来token是有效,则按照解析出来的账号信息查询最新权限数据返回前端
            token = request.getHeader(Constant.JWT_TOKEN);

            if (StringUtils.isNotEmpty(token)) {
                String preAccount = SystemCacheUtil.verifyToken(token);
                if (StringUtils.isNotEmpty(preAccount)) {
                    account = preAccount;
                } else {
                    //说明token失效,将token重置为null
                    token = null;
                }
            }

            if (!StringUtils.isEmpty(accessToken)) {

                // 查询code数据
                JSONObject msg = getUserInfoByToken(accessToken);

                // 查询条件字符串转对象，查询数据结果
                account = msg.getString("loginName");
                if (StringUtils.isEmpty(account)) {
                    setSSORedirectHeader(response);
                    return Response.fail("未找到该账号登录oa信息");
                }
            }
        }

        if (StringUtils.isEmpty(account)) {
            log.error("登录账号为空");
            //响应设置 状态码及重定向地址,参数与前端约定. 302 redirecturl
            setSSORedirectHeader(response);
            return Response.fail("登录账号为空");
        }

        // 校验本系统用户表是否有对应账号
        Response res = staffService.queryStaffInfo(account);
        if (!(res.getCode() == 200 && res.getData() != null)) {
            setSSORedirectHeader(response);
            return Response.fail("系统没有该账号信息");
        }

        eamUser = JSON.parseObject(JSON.toJSONString(res.getData()), EamUser.class);

        //返回登录成功信息，前端可做跳转首页处理或者后台直接重定向到系统首页
        //cas认证通过，然后根据信息返回token
        if (StringUtils.isEmpty(token)) {
            token = SystemCacheUtil.getNewToken(eamUser.getAccount(), eamUser.getName());
        }

        List<String> userTokenList = new ArrayList<>();

        //redis拿出原来tokenList
        EamUser redisUser = SystemCacheUtil.getRedisUser(eamUser.getAccount());
        if (!Objects.isNull(redisUser) && CollectionUtils.isNotEmpty(redisUser.getTokenList())) {
            userTokenList = redisUser.getTokenList();
        }
        eamUser.setTokenList(userTokenList);
        SystemCacheUtil.cacheUserInfo(eamUser, token);

        if (response != null) {
            response.setHeader(Constant.JWT_TOKEN, token);
        }
        return Response.ok("登录成功", eamUser);
    }

    private void setSSORedirectHeader(HttpServletResponse response) {
        response.setHeader("redirecturl", authorizeUrl);
        response.setStatus(HttpStatus.FOUND.value());
    }

    public Boolean defaultInfo(EamUser eamUser, HttpServletResponse response) throws IOException {

        List<OrgVo> orgVoList = eamUser.getOrgVoList();
        List<AppSimpleBean> appSimpleBeanList = eamUser.getAppSimpleBeanList();

        if (CollectionUtils.isNotEmpty(orgVoList) && orgVoList.size() == 1
                && CollectionUtils.isNotEmpty(appSimpleBeanList)
                && appSimpleBeanList.size() == 1) {

            //返回登录成功信息，前端可做跳转首页处理或者后台直接重定向到系统首页
            //cas认证通过，然后根据信息返回token
            String token = SystemCacheUtil.getNewToken(eamUser.getAccount(), eamUser.getName());

            List<String> userTokenList = new ArrayList<>();

            //redis拿出原来tokenList
            EamUser redisUser = SystemCacheUtil.getRedisUser(eamUser.getAccount());
            if (!Objects.isNull(redisUser) && CollectionUtils.isNotEmpty(redisUser.getTokenList())) {
                userTokenList = redisUser.getTokenList();
            }
            eamUser.setTokenList(userTokenList);
            SystemCacheUtil.cacheUserInfo(eamUser, token);

            if (response != null) {
                response.setHeader(Constant.JWT_TOKEN, token);
            }
            log.info("auth 重定向前台页面:{}", workStationPage);
            //附加上水司+组织
            StringBuilder sb = new StringBuilder();
            sb.append(token);
            sb.append("&currDs="+appSimpleBeanList.get(0).getAppMark());
            sb.append("&currOrg="+orgVoList.get(0).getId());

            response.sendRedirect(workStationPage + sb.toString());
            return true;
        }
        return false;
    }



}
